<?php
namespace app\api\controller\salesman;

use think\Controller;
use think\Request;
use think\Db;
use app\common\model\power\Rolepower;
use app\common\model\user\User as UserModel;
use app\api\controller\Base;
use think\facade\Env;
use app\api\controller\Pub;
class Orders extends Base
{
    public function initialize()
    {
        parent::initialize();
        $this->is_login();
        Rolepower::powerguard('305006'); // 销售订单管理权限
    }

    private function is_login()
    {
        $data =UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }

    //产品列表
    public function productList()
    {
        $devices = Db::name('device')->select();
        $accessories = Db::name('accessories')->select();
        $productMap = [];
        foreach ($devices as $device) {
            $device['accessories'] = [];
            $productMap[$device['id']] = $device;
        }
        foreach ($accessories as $accessory) {
            $deviceId = $accessory['device_id'];
            if (isset($productMap[$deviceId])) {
                $productMap[$deviceId]['accessories'][] = $accessory;
            }
        }
        $result = array_values($productMap);
        return myok($result);
    }

    //拆单
    public function productOrder(Request $request)
    {
        $data = $request->post();
        // 验证必要参数
        if (empty($data['contract_id']) || empty($data['devices_id']) || empty($data['accessories_id']) || empty($data['customer_id'])) {
            return json(['code' => 0, 'msg' => '参数不完整']);
        }
    
        // 获取设备信息并按 factory_id 分组
        $devices = Db::name('device')
            ->whereIn('id', $data['devices_id'])
            ->select();
        
        //生成流量卡订单
        //流量卡数量()
        $card_count=Db::name('device')->whereIn('id', $data['devices_id'])->where('is_need',1)->count();
        $accessory_id=Db::name('accessories')->where('name','like','%'.'流量卡x'.$card_count.'%')->column('id');
        $accessory_id=$accessory_id[0];
        $cardData['contract_id']=$data['contract_id'];
        $cardData['customer_id']=$data['customer_id'];
        $cardData['accessories_id']=$accessory_id;
        $cardData['device_id']=1;
        $cardData['factory_id']=1;
        $cardData['status']=1;
        $cardData['create_time']=time();
        $cardData['update_time']=time();
        // 流量卡的订单ID。
        $cardOrderId=Db::name('contract_order')->insertGetId($cardData);

        if (count($devices) != count($data['devices_id'])) {
            return json(['code' => 0, 'msg' => '部分设备ID不存在']);
        }
        // 按 factory_id 分组设备
        $devicesByFactory = [];
        foreach ($devices as $device) {
            $factoryId = $device['factory_id'];
            $devicesByFactory[$factoryId][] = $device;
        }
        
        // 获取配件信息并构建设备ID到配件的映射
        $accessories = Db::name('accessories')
            ->whereIn('id', $data['accessories_id'])
            ->select();
        
        $deviceAccessoriesMap = [];
        foreach ($accessories as $accessory) {
            $deviceAccessoriesMap[$accessory['device_id']][] = $accessory['id'];
        }
        
        // 为每个 factory_id 创建订单
        $currentTime = time();
        $orderIds = [];
        
        try {
            Db::startTrans(); // 开启事务
            
            foreach ($devicesByFactory as $factoryId => $factoryDevices) {
                // 当前厂商的设备ID
                $factoryDeviceIds = array_column($factoryDevices, 'id');
                
                // 当前设备组的所有配件ID
                $factoryAccessoryIds = [];
                foreach ($factoryDeviceIds as $deviceId) {
                    if (isset($deviceAccessoriesMap[$deviceId])) {
                        $factoryAccessoryIds = array_merge($factoryAccessoryIds, $deviceAccessoriesMap[$deviceId]);
                    }
                }
                
                // 准备订单数据
                $orderData = [
                    'contract_id' => $data['contract_id'],
                    'device_id' => implode(',', $factoryDeviceIds), 
                    'accessories_id' => implode(',', array_unique($factoryAccessoryIds)),
                    'factory_id' => $factoryId,
                    'customer_id' => $data['customer_id'],
                    'track_number' => $data['track_number'] ?? '',
                    'status' => 1,
                    'create_time' => $currentTime,
                    'update_time' => $currentTime
                ];
                
                // 插入订单并记录订单ID
                $orderId = Db::name('contract_order')->insertGetId($orderData);
                $orderIds[] = $orderId;
                
            }
            //将流量卡的订单ID加入到订单ID中。
            array_unshift($orderIds,$cardOrderId);
            Db::commit(); // 提交事务
            
            return json(['code' => 1, 'msg' => '生成订单成功', 'order_ids' => $orderIds]);
        } catch (\Exception $e) {
            Db::rollback(); // 回滚事务
            return json(['code' => 0, 'msg' => '生成订单失败：' . $e->getMessage()]);
        }
    }

    //有客户信息和合同信息的订单列表
    public function orderList(Request $request)
    {
        $pub = new Pub();
        $user_id = $pub->userid();
        $role = Db::name('user')->where('UserId', $user_id)->value('Role');
        
        if ($role == 305) { // 销售管理员
            $group_id = Db::name('user_group')->where('user_id', $user_id)->value('group_id');
            $emp_ids = Db::name('user_group')->where('group_id', $group_id)->column('user_id');
            $customer_ids = Db::name('user_customer')->whereIn('user_id', $emp_ids)->column('customer_id');
        } elseif ($role == 306) { // 销售员工
            $customer_ids = Db::name('user_customer')->where('user_id', $user_id)->column('customer_id');
        } else {
            return json(['code' => 0, 'msg' => '权限不足']);
        }
        
        if (empty($customer_ids)) {
            return json(['code' => 1, 'msg' => 'success', 'data' => []]);
        }
        
        $orders = Db::name('contract_order')
            ->alias('o')
            ->join('product_contract c', 'o.contract_id = c.id', 'LEFT')
            ->join('customer cu', 'o.customer_id = cu.CustomerId', 'LEFT')
            ->whereIn('o.customer_id', $customer_ids)
            ->order('create_time desc')
            ->field([
                'o.*',
                'c.name as contract_name',    // 合同名称
                'c.img_url as contract_img_url', // 合同凭证
                'cu.Name as customer_name',   // 客户姓名
                'cu.Address as customer_address', // 客户地址
                'cu.Tel as customer_tel'      // 客户电话
            ])
            ->select();

        foreach ($orders as &$order) {
            $order['device'] = Db::name('device')
                ->whereIn('id', explode(',', $order['device_id']))
                ->field('id, name')
                ->select();
            
            $accessories = isset($order['accessories_id']) 
                ? Db::name('accessories')->whereIn('id', explode(',', $order['accessories_id']))->select() 
                : [];
            
            $accessoriesByDevice = [];
            foreach ($accessories as $acc) {
                $accessoriesByDevice[$acc['device_id']][] = $acc;
            }
            foreach ($order['device'] as &$dev) {
                $dev['accessories'] = $accessoriesByDevice[$dev['id']] ?? [];
            }
            unset($dev);
            unset($order['device_id'], $order['accessories_id']);
            $order['create_time'] = date('Y-m-d H:i:s', $order['create_time']);
            $order['update_time'] = date('Y-m-d H:i:s', $order['update_time']);
        }
        
        return json(['code' => 1, 'msg' => 'success', 'data' => $orders]);
    }

    //订单状态修改
    public function orderStatusChange(Request $request)
    {
        $data = $request->post();
        if (empty($data['id']) || empty($data['track_number']) || empty($data['status'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $order = Db::name('contract_order')->where('id', $data['id'])->find();
        if (!$order) {
            return json(['code'=>0, 'msg'=>'订单不存在']);
        }
        Db::name('contract_order')->where('id', $data['id'])->update([
            'track_number' => $data['track_number'],
            'status' => $data['status'],
            'update_time' => time()
        ]);
        return json(['code'=>1, 'msg'=>'修改成功']);
    }

} 